package info.magnolia.blossom.sample.cv.components;

import info.magnolia.blossom.sample.cv.ListOfCVs;
import info.magnolia.blossom.sample.cv.model.CurriculumVitae;
import info.magnolia.blossom.sample.cv.service.CVService;
import info.magnolia.module.blossom.annotation.TabFactory;
import info.magnolia.module.blossom.annotation.Template;
import info.magnolia.module.blossom.annotation.TemplateDescription;
import info.magnolia.module.blossom.dialog.TabBuilder;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * User: peterbalazs
 * Date: 3/6/13
 * Time: 10:12 AM
 * To change this template use File | Settings | File Templates.
 */
@Template(title = "Edit CV", id = "blossomSample:components/editcv")
@TemplateDescription("Edit CV component")
@Controller
public class EditCVComponent {

    private static final String ERROR_MSG = "errorMsg";
    private static final String ERROR_PAGE_PATH = "components/error.jsp";

    /**
     * Class logger.
     */
    private static final Logger logger = Logger.getLogger(EditCVComponent.class);

    @Autowired
    private CVService cvService;

    @RequestMapping("/cvtemplate/editcv")
    public String render(final ModelMap model, final HttpServletRequest request) {
        final String id = request.getParameter(ListOfCVs.PARAM_CV_ID);
        try {
            if (StringUtils.isBlank(id)) {
                throw new IllegalArgumentException("CV ID missing");
            }
            final CurriculumVitae cv = cvService.getCV(id);
            if (cv == null) {
                throw new IllegalArgumentException("CV with ID " + id + " cannot be found");
            }
            model.put("cvForm", cv);
        } catch (Exception e) {
            logger.error("Error editing CV with ID " + id, e);
            model.put(ERROR_MSG, "Error editing CV:</br>" + e.getMessage());
            return ERROR_PAGE_PATH;
        }
        return "components/editCV.jsp";
    }

    @TabFactory("Settings")
    public void settingsTab(final TabBuilder tab) {
        tab.addUuidLink("editSavedLink", "Update Saved Page", "Browse and select the page which confirms the CV update");
    }
}
